// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/


#[tauri::command]
fn run_script(script_path: String, args: Vec<String>) -> Result<String, String> {
    use std::process::Command;
    
    // 获取当前可执行文件所在目录
    let exe_dir = std::env::current_exe()
        .map_err(|e| e.to_string())?
        .parent()
        .ok_or("无法获取父目录")?
        .to_path_buf();

    // 构建完整的脚本路径
    let full_script_path = exe_dir.join(script_path);
    
    // 执行命令
    let output = if cfg!(target_os = "windows") {
        Command::new("cmd")
            .arg("/C")
            .arg(full_script_path)
            .args(args)
            .output()
            .map_err(|e| e.to_string())?
    } else {
        Command::new("sh")
            .arg(full_script_path)
            .args(args)
            .output()
            .map_err(|e| e.to_string())?
    };
    
    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).to_string())
    }
}


#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![run_script])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
